#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from dws.commons.common import log
from common.util.check_utils import is_valid_id
from dws.commons.parse_param import parse_param_with_jsonschema
from common.common import output_result_file, exter_attack
from common.common_models import SubJobDetails
from common.const import SubJobStatusEnum
from dws.backup.cluster_backup import ClusterBackup
from dws.commons.dws_param_parse import DwsParamParse
from dws.commons.job_info import JobInfo


def is_post_job(job_name):
    if 'post_job' in job_name:
        return True
    return False


def is_sub_backup_job(param):
    if not param.get('subJob'):
        return False
    if 'backup' == param.get('subJob').get("jobName"):
        return True
    return False


@exter_attack
def do_exec(post_job, pid):
    param = parse_param_with_jsonschema(pid)

    job_info = JobInfo(pid=pid,
                       job_id=DwsParamParse.get_job_id(param),
                       copy_id=DwsParamParse.get_copy_id(param),
                       sub_job_id=DwsParamParse.get_sub_job_id(param),
                       cache_path=DwsParamParse.get_cache_path(param),
                       backup_tool_type=DwsParamParse.get_backup_tool_type(param),
                       cluster_agents=DwsParamParse.get_cluster_agents(param),
                       host_agents=DwsParamParse.get_host_agents(param),
                       data_reps=DwsParamParse.get_data_reps(param))

    try:
        if not ClusterBackup(pid).get_progress(job_info, post_job, is_sub_backup_job(param)):
            raise Exception("Get progress failed")
    except Exception as err_str:
        output_result_file(
            pid,
            SubJobDetails(taskId=DwsParamParse.get_job_id(param),
                          subTaskId=DwsParamParse.get_sub_job_id(param),
                          progress=0,
                          speed=0,
                          taskStatus=SubJobStatusEnum.FAILED.value).dict(by_alias=True))
        log.error(f"{err_str}, finish to write result. {job_info.log_format()}")
        return False

    log.info(f"Get progress suc. pid: {pid}, {job_info.log_format()}")
    return True


if __name__ == '__main__':
    """获取任务进度任务"""
    if not is_valid_id(sys.argv[2]):
        log.warn(f"pid is invalid")
        sys.exit(1)

    try:
        if not do_exec(is_post_job(sys.argv[1]), sys.argv[2]):
            sys.exit(1)
    except Exception as err:
        log.error(f"Err: {err}, pid: {sys.argv[2]}")
        sys.exit(1)

    sys.exit(0)
